package cz.acies.genea.data.gedcom.tools;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.BeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.xml.sax.SAXParseException;

import cz.acies.data.DBConnector;
import cz.acies.genea.data.gedcom.model.EventFact;
import cz.acies.genea.data.gedcom.model.Family;
import cz.acies.genea.data.gedcom.model.Gedcom;
import cz.acies.genea.data.gedcom.model.Name;
import cz.acies.genea.data.gedcom.model.ParentFamilyRef;
import cz.acies.genea.data.gedcom.model.Person;
import cz.acies.genea.data.gedcom.model.SpouseFamilyRef;
import cz.acies.genea.data.gedcom.model.SpouseRef;
import cz.acies.genea.data.gedcom.parser.ModelParser;
import cz.acies.genea.data.persist.GedFamily;
import cz.acies.genea.data.persist.GedPerson;

public class Tester
{
	private File gedcomIn = new File("d:/backup/data/genea/data2.ged");
	//private File jsonOut = new File("d:/backup/data/genea/data.json");
	//private boolean useTreeParser = true;

	public static void main(String[] args) {
		//Gedcom2Json self = new Gedcom2Json();
		try {
			Tester inst = new Tester(); 
			//inst.resonsLoad();
			inst.doMain();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void resonsLoad() throws Exception {
		try {
			/*
			String id = "GE.R.000000000000001";
			String tableName = "person";
			//String sql = "SELECT * FROM "+tableName+" WHERE "+tableName+".ID = '"+id+"' ";
			String sql = "SELECT * FROM "+tableName;
			QueryRunner qr = new QueryRunner(DBConnector.instance().getDataSource());
			ResultSetHandler<List<GPerson>> handler = new BeanListHandler<GPerson>(GPerson.class, 
				new BasicRowProcessor(new BeanProcessor() {
					@Override
					protected Object processColumn(ResultSet rs, int index, Class<?> propType) throws SQLException {
						System.out.println("BeanProcessor.processColumn("+index+",  "+propType+")");
						if (propType == GFamily.class) {
							String id = rs.getString(index);
							return new GFamily(id);
						} else {
							return super.processColumn(rs, index, propType);
						}
					}
				}) 
			);
			List<GPerson> records = qr.query(sql, handler);

			//List<Map<String, Object>> list = qr.query(sql, new DefaultMapListHandler(new DefaultRowProcessor()));
			System.out.println(records);
			*/
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}
	
	public void doMain() throws SAXParseException, IOException {
		String json;
		//JsonParser jsonParser = new JsonParser();
		String dir = "d:/java/repository/acies/genea/UR.M.000000000000001";
		String fn = "Dytrych-Jaroslav-201312130335.ged";
		//String fn = "MH-Dytrych.Jaroslav.201312150719.GED";
		
		//"y:/backup/gg-disk/data/genea/Dytrych.Jaroslav.201309040727.ged";
		String path = dir+"/"+fn;

		gedcomIn = new File(path);
		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
		
		ModelParser modelParser = new ModelParser();
		Gedcom gedcom = modelParser.parseGedcom(gedcomIn);
		
		Map<String, GedPerson> people = new LinkedHashMap<String, GedPerson>(); 
		
		for (Family f : gedcom.getFamilies()) {
			//System.out.println(f.getId() + " " + f.getHusbandRefs());
			GedFamily family = new GedFamily();
			String id = f.getId();
			if (!f.getHusbandRefs().isEmpty()) {
				SpouseRef sposes = f.getHusbandRefs().get(0);
				String xref = sposes.getRef();
			}
			if (!f.getWifeRefs().isEmpty()) {
				SpouseRef sposes = f.getWifeRefs().get(0);
			}
		}
		/*
		List<Person> people = gedcom.getPeople();
		for (Person person : people) {
			Map<String, Object> row = new HashMap<String, Object>();
			
			row.put("id", person.getId());
			List<Name> names = person.getNames();
			for (Name name : names) {
				String displayName = name.getDisplayValue();
				
				int pos = displayName.indexOf("/");
				String firstName = (pos > 0) ? displayName.substring(0, pos) : "";
				String maidenName = (pos > 0) ? displayName.substring(pos).replace("/", "") : "";
				String lastName = name.getMarriedName();
				if (lastName == null || lastName.length() == 0) lastName = maidenName;
				
				row.put("firstName", firstName);
				row.put("lastName", lastName);
				row.put("maidenName", maidenName);
				break;
			}
			List<EventFact> efs = person.getEventsFacts();
			for (EventFact ef : efs) {
				String key = ef.getTag();
				if (key.equals("SEX")) {
					row.put("gender", ef.getValue());
				} else if (key.equals("BIRT")) {
					row.put("birthDate", ef.getDate());
					row.put("birthPlace", ef.getPlace());
				} else if (key.equals("DEAT")) {
					row.put("deathDate", ef.getDate());
					row.put("deathPlace", ef.getPlace());						
				}
			}
	*/
			/*
			List<ParentFamilyRef> parents = person.getParentFamilyRefs();
			for (ParentFamilyRef pf : parents) {
				// FAMC
				System.out.println(
					"FAMC: "+pf.getRef() + " " + pf.getExtensions()+" "+pf.getRelationshipType()
				);
			}
			List<SpouseFamilyRef> partners = person.getSpouseFamilyRefs();
			for (SpouseFamilyRef partner : partners) {
				System.out.println("FAMS: "+partner.getRef());
			}
			*/
	/*
			//System.out.println(person.getParentFamilyRefs());
			
			System.out.println(row);
			data.add(row);
			System.out.println("----------");
		}
		System.out.println("\n");
		
		List<Family> families = gedcom.getFamilies();
		for (Family family : families) {
			System.out.println(family.getId() + ", " + family.getUid());
		}
		//gedcom.getFamily("");
		System.out.println("\n");
		for (Map<String, Object> row : data) {
			System.out.println(row);
		}
	*/
	}
}
